/*
 * Copyright (C) 2017 zhouyou(478319399@qq.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.shuyihui.rxhttp.cookie

import android.content.Context
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl
import java.util.*

/**
 *
 * 描述：cookie管理器
 */
class CookieManger(private val mContext: Context) : CookieJar {
    fun addCookies(cookies: List<Cookie>) {
        Companion.cookieStore!!.addCookies(cookies)
    }

    fun saveFromResponse(url: HttpUrl, cookie: Cookie) {
        if (cookie != null) {
            Companion.cookieStore!!.add(url, cookie)
        }
    }

    val cookieStore: PersistentCookieStore?
        get() = Companion.cookieStore

    override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
        if (cookies != null && cookies.size > 0) {
            for (item in cookies) {
                Companion.cookieStore!!.add(url, item)
            }
        }
    }

    override fun loadForRequest(url: HttpUrl): List<Cookie> {
        val cookies = Companion.cookieStore!![url]
        return cookies ?: ArrayList()
    }

    fun remove(url: HttpUrl, cookie: Cookie) {
        Companion.cookieStore!!.remove(url, cookie)
    }

    fun removeAll() {
        Companion.cookieStore!!.removeAll()
    }

    companion object {
        private var cookieStore: PersistentCookieStore? = null
    }

    init {
        if (Companion.cookieStore == null) {
            Companion.cookieStore = PersistentCookieStore(mContext)
        }
    }
}